package org.jeecg.modules.basesource.handler;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.modules.basesource.service.IDjNsrzyxxService;
import org.jeecg.modules.basesource.service.IDjPzjgxxService;
import org.jeecg.modules.dzswj.GuangdongSfjrApiService;
import org.jeecg.modules.dzswj.exception.SmdlException;
import org.jeecg.modules.dzswj.vo.LoginSessionVo;
import org.jeecg.modules.dzswj.vo.response.DzswjBaseResponse;
import org.jeecg.modules.dzswj.vo.response.PzjgxxVo;
import org.jeecg.modules.dzswj.vo.response.nsrxxcx.Nsrjbxx;
import org.jeecg.modules.dzswj.vo.response.nsrxxcx.NsrxxCxResponseVo;
import org.jeecg.modules.qyxx.entity.CjQyxxStatus;
import org.jeecg.modules.qyxx.entity.DjNsrxxSyncRecord;
import org.jeecg.modules.qyxx.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.concurrent.*;

/**
 * @author chensherun on 2022/3/14.
 * @version 1.0
 */
@Slf4j
@Component
public class NsrjbxxSyncHandler {

    @Autowired
    private ICjQyxxStatusService cjQyxxStatusService;

    @Autowired
    private IDjNsrxxService djNsrxxService;

    @Autowired
    private IDjNsrxxSyncRecordService nsrxxSyncRecordService;

    @Autowired
    private GuangdongSfjrApiService sfjrApiService;

    private static ExecutorService executor = new ThreadPoolExecutor(3, 5, 0L,
            TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(10000),
            new ThreadPoolExecutor.CallerRunsPolicy());

    @XxlJob("nsrjbxxCj")
    public ReturnT<String> nsrjbxxCj(String param) {
        String tynsrsbh = null;
        JSONObject jsonObject = JSONObject.parseObject(param);
        if (jsonObject != null) {
            tynsrsbh = jsonObject.getString("tynsrsbh");
        }
        LambdaQueryWrapper<CjQyxxStatus> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CjQyxxStatus::getType, "01").eq(CjQyxxStatus::getStatus, "0");
        if (StringUtils.isNotBlank(tynsrsbh)) {
            queryWrapper.eq(CjQyxxStatus::getNsrsbh, tynsrsbh);
        }
        List<CjQyxxStatus> list = cjQyxxStatusService.list(queryWrapper);
        List<Future> futureList = new ArrayList<>();
        for (CjQyxxStatus cjQyxxStatus : list) {
            futureList.add(executor.submit(new Callable() {
                @Override
                public Object call() throws Exception {
                    //每三个月才直接去同步一次信息,所以
                    String cjTynsrsbh = cjQyxxStatus.getDjxh();
                    Date jssj = cjQyxxStatus.getJssj();
                    Calendar jssjCal = Calendar.getInstance();
                    jssjCal.setTime(jssj);
                    int month = jssjCal.get(Calendar.MONTH) + 1;
                    List<Integer> syncMonth = Arrays.asList(3, 6, 9, 12);
                    //一个季度更新一次即可，其余月份直接成功
                    if (!syncMonth.contains(month)) {
                        cjQyxxStatus.setStatus("1");
                        cjQyxxStatusService.updateByMultiId(cjQyxxStatus);
                    } else {
                        DjNsrxxSyncRecord nsrxxSyncRecord = new DjNsrxxSyncRecord();
                        nsrxxSyncRecord.setDjxh(cjTynsrsbh);
                        nsrxxSyncRecord.setNsrsbh(cjTynsrsbh);
                        try {
                            LoginSessionVo loginInfo = sfjrApiService.getNsrLoginSessionInfo(cjTynsrsbh);
                            NsrxxCxResponseVo nsrxxCxResponseVo = sfjrApiService.nsrxxCx(loginInfo.getSessionId(), loginInfo.getZgswjdm(), loginInfo.getDjxh());
                            Nsrjbxx nsrjbxx = nsrxxCxResponseVo.getNsrjbxx();
                            List<PzjgxxVo> pzjgxxVoList = null;
                            try {
                                DzswjBaseResponse<List<PzjgxxVo>> pzjgxxResponse = sfjrApiService.nsrxxPzjgxx(loginInfo.getSessionId(), nsrjbxx.getZgswjdm(), cjTynsrsbh);
                                pzjgxxVoList = pzjgxxResponse.getBody();
                            } catch (Exception e) {
                                log.error("查询批准机构信息失败,tynsrsbh：{}, 错误信息:{}", cjTynsrsbh, e.getMessage(), e);
                            }
                            djNsrxxService.saveOrUpdateNsrjbxxAndPzjg(nsrxxCxResponseVo, pzjgxxVoList);
                            //修改成同步成功
                            cjQyxxStatus.setStatus("1");
                            cjQyxxStatusService.updateByMultiId(cjQyxxStatus);
                            nsrxxSyncRecord.setStatus("100");
                            nsrxxSyncRecord.setRemark("同步成功");
                        } catch (Exception e) {
                            log.error("同步纳税人信息失败,", e);
                            String errorMsg = e.getMessage();
                            if (e instanceof SmdlException) {
                                nsrxxSyncRecord.setStatus("-2");
                                errorMsg = "【" + ((SmdlException) e).getErrorCode().getCode() + "】" + e.getMessage();
                            } else {
                                nsrxxSyncRecord.setStatus("-1");
                            }
                            nsrxxSyncRecord.setRemark(errorMsg);
                        }
                        try {
                            nsrxxSyncRecordService.save(nsrxxSyncRecord);
                        } catch (Exception e) {
                            log.error("保存纳税人信息同步出错", e);
                        }
                    }
                    return null;
                }
            }));
        }
        return ReturnT.SUCCESS;
    }
}
